package cn.edu.fzu.delivery.helper;

import cn.edu.fzu.delivery.http.HttpClientFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.concurrent.ExecutorService;

/**
 * 系统下线
 *
 * @author fangxin
 * @date 2022/11/16
 */
@Component
public class ShutDownHelper {

    @Resource
    private ExecutorService threadPool;

    @PostConstruct
    public void load() {
        DingDingRobot.delivery().send("快递系统部署通知", "前后端均部署成功", Collections.singletonList("http://101.43.44.19/"), null,
                null);
    }


    @PreDestroy
    public void shutdown() {
        DingDingRobot.delivery().send("快递系统下线通知", "请各位注意，系统即将下线", Collections.singletonList("http://101.43.44.19/"),
                null, null);
        //关闭钉钉机器人
        DingDingRobot.shutdownAll();
        //关闭http链接池
        HttpClientFactory.close();
        //关闭线程池
        threadPool.shutdown();
    }


    /**
     * 执行部署功能
     * 
     * @return 是否执行成功
     */
    public static String deploy() {
        String commend = "/home/ubuntu/deploy.sh &";
        Process proc = null;
        try {
            Runtime rt = Runtime.getRuntime();
            proc = rt.exec(commend);
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            int exitVal = proc.waitFor();
            if (exitVal == 0) {
                return null;
            } else {
                return String.valueOf(exitVal);
            }
        } catch (Exception e) {
            return e.getMessage();
        } finally {
            if (proc != null) {
                proc.destroy();
            }
        }
    }
}
